package com.example.administrator.mybabymall.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;
import com.example.administrator.mybabymall.BaseAdapter.BaseAdapter;
import com.example.administrator.mybabymall.Contants;
import com.example.administrator.mybabymall.R;
import com.example.administrator.mybabymall.adapter.HotWaresAdapter;
import com.example.administrator.mybabymall.bean.Page;
import com.example.administrator.mybabymall.bean.Wares;
import com.example.administrator.mybabymall.util.DividerItemDecoration2;
import com.google.gson.Gson;
import com.lidroid.xutils.ViewUtils;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/12/22 0022.
 */

public class FragmentTwo extends Fragment {
    private int currentPage = 1;
    private int pageSize=10;
    private List<Wares> mWares = new ArrayList<>();
    private HotWaresAdapter mHotWaresAdapter;

    private RecyclerView mRecyclerView;
    private Gson gson = new Gson();
    private int totalpage;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what == 1){
//              接收异步OKHTTP传来的数据
                String result = (String) msg.obj;
                Page page = gson.fromJson(result,Page.class);
                mWares = page.getList();
                currentPage = page.getCurrentPage();
                totalpage = page.getTotalPage();
                showData();
            }

        }
    };

    private static final int STATE_NORMAL = 0;
    private static final int STATE_REFRESH = 1;
    private static final int STATE_MORE = 2;
    private int state = STATE_NORMAL;

    private MaterialRefreshLayout materialRefreshLayout;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_two, container, false);
        ViewUtils.inject(view);
        mRecyclerView = view.findViewById(R.id.recyclerview);
        materialRefreshLayout = view.findViewById(R.id.refresh_hot);
        initRefresh();
        outputJson(1);
        return view;
    }

    private void initRefresh(){
        materialRefreshLayout.setLoadMore(true);
        materialRefreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {
            @Override
            public void onRefresh(MaterialRefreshLayout materialRefreshLayout) {
                refreshData();
            }

            @Override
            public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout) {
                if (currentPage <= totalpage+1)
                    loadData();
                else {
//                    超页提示
                    materialRefreshLayout.finishRefreshLoadMore();
                }
            }
        });
    }

    private void refreshData(){
        currentPage = 1;
        state = STATE_REFRESH;
        outputJson(1);
    }

    private void loadData(){
        currentPage = ++currentPage;
        state = STATE_MORE;
        outputJson(1);
    }

    private void showData(){

        switch (state){
            case STATE_NORMAL:
                mHotWaresAdapter = new HotWaresAdapter(mWares,getContext());
//                mHotWaresAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
//                    @Override
//                    public void onClick(View view, int position) {
//                        Toast.makeText(getContext(),"which is clicked:"+position,Toast.LENGTH_SHORT).show();
//                    }
//                });
                mRecyclerView.setAdapter(mHotWaresAdapter);
                mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
                mRecyclerView.setItemAnimator(new DefaultItemAnimator());
                mRecyclerView.addItemDecoration(new DividerItemDecoration2(getContext(),DividerItemDecoration2.VERTICAL_LIST));
                break;
            case STATE_REFRESH:
                mHotWaresAdapter.cleanData();
                mHotWaresAdapter.addData(mWares);
                mRecyclerView.scrollToPosition(0);
                materialRefreshLayout.finishRefresh();
                break;
            case STATE_MORE:
                mHotWaresAdapter.addData(mHotWaresAdapter.getDatas().size(),mWares);
                mRecyclerView.scrollToPosition(mHotWaresAdapter.getDatas().size());
                materialRefreshLayout.finishRefreshLoadMore();
                break;
        }

    }

    //    OKhttp获取URL  Json数据
    private  void outputJson( final int num) {

        OkHttpClient okHttpClient = new OkHttpClient();
        String url = Contants.API.WARES_HOT+"?curPage="+currentPage+"&pageSize="+pageSize;
        Request request = new Request.Builder()
                .url(url)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                Log.e("OKHTTP:", "ERROR");
            }

            @Override
            public void onResponse(Response response) throws IOException {
                if (response.isSuccessful()) {
                    String str = response.body().string();
//                    Log.v("OKHTTP:", "json:" + str);
                    Message message = Message.obtain();
                    message.what = num;
                    message.obj = str;
                    handler.sendMessage(message);
                } else {
                    Log.v("Response", "访问失败");
                }

            }

        });

    }
}
